//
//  YZXTextView.swift
//  YZXWeibo
//
//  Created by 叶周翔 on 16/7/28.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit

class YZXTextView: UITextView {
    var placeholder:String?{
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        self.setUpUI()
        
        // 当 UITextView 中的文本的内容改变的时候 会自动发送一个名字为 UITextViewTextDidChangeNotification 的通知 然后在外面去监听这个通知  在一个项目中有可能会有多个 UITextView 所以只监听自己发送的这个通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    private func setUpUI(){
    
        self.addSubview(placeholderLabel)
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        // 约束
        self.addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 4))
        
        self.addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
    
        
    }
    
    
    
    //MARK:监听通知的方法
    @objc private func textViewDidChange(){
        // 占位文本的隐藏
        self.placeholderLabel.hidden = self.hasText()
    }
    
    
    
    // MARK:懒加载
    private lazy var placeholderLabel:UILabel = {
       let label = UILabel()
        label.textColor = UIColor.lightGrayColor()
        label.font = UIFont.systemFontOfSize(14)
        
        return label
    }()
}
